<?
function ldapUpdate ($itemId = 0)
{
	$section = Business::singleton ()->getSection (Section::TCURRENT);

	if (!Security::singleton ()->getUserType ($section->getName ())->useLdap ())
		return TRUE;

	if (!Security::singleton ()->getUserType ($section->getName ())->getLdap ()->updateOnLogon ())
		return TRUE;

	$userType = Security::singleton ()->getUserType ($section->getName ());

	$db = Database::singleton ();

	if ($itemId)
	{
		$sth = $db->prepare ("SELECT _login, _name FROM _user WHERE _type = '". $section->getName () ."' AND _deleted = '0' AND _id = '". $itemId ."'");

		$sth->execute ();

		$user = $sth->fetch (PDO::FETCH_OBJ);

		if (!$user)
			throw new Exception (__('Unable to recover user data from database!'));

		$form = Form::singleton ($userType->getLdapForm (), 'edit.xml', 'all.xml');

		if (!$form->load ($itemId))
			throw new Exception (__('Unable to load your private data from user [1] [ [2] ]', $user->_name, $user->_login));

		if (!$form->loadFromLdap ($user->_login, $userType->getLdap ()))
			throw new Exception (__('Unable to load LDAP server data to the user [1] [ [2] ]', $user->_name, $user->_login));

		if (!$form->save ($itemId, FALSE))
			throw new Exception (__('Unable to save the database data from LDAP server to the user [1] [ [2] ]', $user->_name, $user->_login));
	}
	else
	{
		$sth = $db->prepare ("SELECT _login, _id, _name FROM _user WHERE _type = '". $section->getName () ."' AND _deleted = '0'");

		$sth->execute ();

		$form = Form::singleton ($userType->getLdapForm (), 'edit.xml', 'all.xml');

		while ($user = $sth->fetch (PDO::FETCH_OBJ))
		{
			try
			{
				if (!$form->load ($user->_id))
					throw new Exception (__('Unable to load your private data from user [1] [ [2] ]', $user->_name, $user->_login));

				if (!$form->loadFromLdap ($user->_login, $userType->getLdap ()))
					throw new Exception (__('Unable to load LDAP server data to the user [1] [ [2] ]', $user->_name, $user->_login));

				if (!$form->save ($user->_id, FALSE))
					throw new Exception (__('Unable to save the database data from LDAP server to the user [1] [ [2] ]', $user->_name, $user->_login));
			}
			catch (Exception $e)
			{
				Message::singleton ()->addWarning ($e->getMessage ());
			}
		}
	}

	return TRUE;
}
?>